from redis import asyncio as aioredis
from fastapi import FastAPI


def register_redis(app: FastAPI, config: dict):
    """
    Redis注册函数
    @param app: FastAPI 应用对象
    @param config: dict 配置信息
    """
    async def redis_pool():
        redis = await aioredis.from_url(f"redis://{config.get('username')}:{config.get('password')}@{config.get('host')}:{config.get('port')}/{config.get('db')}", decode_responses=True)
        return redis

    @app.on_event("startup") # 当App应用对象启动时，自动执行这里
    async def startup_event():
        app.state.redis = await redis_pool()
